package com.adong.juc;

import java.sql.SQLOutput;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * lock锁
 * 买票程序复习 三个售票员 卖出 30 张票
 */
public class SaleTicket {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i < 40; i++) {
                    ticket.sale();
                }
            }
        }, "DD").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i < 40; i++) {
                    ticket.sale();
                }
            }
        }, "BB").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i < 40; i++) {
                    ticket.sale();
                }
            }
        }, "BB").start();

        //lambda表达式简写
        new Thread(() -> {
            for (int i = 1; i < 40; i++) ticket.sale();
        }, "AA").start();

    }
}

class Ticket {
    private int number = 30;
    private Lock lock = new ReentrantLock();


    public void sale() {

        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + " 卖出" + number-- + " 号票" + "还剩 " + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    /*public synchronized void sale() {
        if (number > 0) {
            System.out.println(Thread.currentThread().getName() + "卖出" + number-- + "号票" + "还剩" + number);
        }
    }*/
}